//
//  HUDUtils.swift
//  vgbox
//
//  Created by Swift Xcode on 2017/5/19.
//  Copyright © 2017年 Swift Xcode. All rights reserved.
//

import Foundation
import MBProgressHUD

///显示hud
class HUDUtil {
    
    private static var hud: MBProgressHUD!
    private static var progressView: MBRoundProgressView!
    
    ///初始化
    class func initHUD() -> Bool {
        if hud != nil {
            hud.removeFromSuperview()
            hud = nil
        }
        //放到最上层的window
        if let w = UIWindow().frontWindow() {
            hud = MBProgressHUD(view: w)
            w.addSubview(hud)
            return false
        } else {
            return true
        }
    }
    
    /// 黑底 转圈圈
    class func showHud() {
        if initHUD() { return }
        showBlackIndiView(text: nil)
    }
    
    /// 隐藏hud
    class func hideHud() {
        if initHUD() { return }
        hud.hideHud(false)
    }
    
    /// 黑底 转圈圈 + 文字
    class func showBlackIndiView(text: String? = Constant_Toast.loadText) {
        if initHUD() { return }
        var actiView: UIActivityIndicatorView!
        if #available(iOS 13.0, *) {
            actiView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.large)
        } else {
            actiView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge)
        }
        actiView.startAnimating()
        hud.customView = actiView
        hud.bezelView.style = .solidColor
        hud.bezelView.color = UIColor.black.withAlphaComponent(0.7)
        hud.contentColor = UIColor.white
        hud.label.transform = CGAffineTransform(translationX: 0, y: 5)
        hud.mode = .customView
        hud.label.text = text
        hud.label.font = UIFont.systemFont(ofSize: 16)
        hud.detailsLabel.text = nil
        hud.showHud(true)
    }
    
    /// 黑底 文字
    class func showBlackTextView(text: String?, detailText: String? = nil, delay: Double? = 1.5, callback:(() -> Void)? = nil) {
        if initHUD() { return }
        if text == "" { return }
        hud.bezelView.style = .solidColor
        hud.bezelView.color = UIColor.black.withAlphaComponent(0.7)
        hud.contentColor = UIColor.white
        hud.mode = .text
        hud.label.text = text
        hud.label.font = UIFont.systemFont(ofSize: 16)
        hud.label.numberOfLines = 0
        hud.detailsLabel.text = detailText
        hud.detailsLabel.numberOfLines = 0//.SFUIText-Semibold 12.00pt
        hud.showHud(true, delay!) {
            callback?()
        }
        if let delay = delay {
            hud.hideHud(false, delay)
        }
    }
    
    /// 显示成功 图片 + 文字
    class func showHudWithSucceed(text: String?, callback: (() -> Void)?) {
        
        if initHUD() { return }
        hud.customView = UIImageView(image: UIImage(named: "37x-Checkmark-black"))
        hud.mode = .customView
        hud.label.text = text
        hud.detailsLabel.text = nil
        
        hud.showHud(true) {
            callback?()
        }
    }
    
    /// 显示失败 图片 + 文字
    class func showHudWithFailed(text: String?, callback:(() -> Void)?) {
        
        if initHUD() { return }
        hud.customView = UIImageView(image: UIImage(named: "37x-Checkmark-error-black"))
        hud.mode = .customView
        hud.label.text = text
        hud.detailsLabel.text = nil
        hud.showHud(true) {
            callback?()
        }
    }
    
    /// 显示一个view 自定义view + 回调 + 延迟时间
    class func showCustomView(view: UIView?, text: String?, delay: Double? = nil) {
        
        if initHUD() { return }
        hud.customView = view
        hud.bezelView.color = .black
        hud.contentColor = UIColor.white
        hud.label.transform = CGAffineTransform(translationX: 0, y: 5)
        hud.mode = .customView
        hud.label.text = text
        hud.detailsLabel.text = nil
        hud.showHud(true)
        if let delay = delay {
            hud.hideHud(false, delay)
        }
    }
    
    class func showWarCustomView(icon: String?, text: String?, delay: Double? = nil) {
        
        if initHUD() { return }
        var string:NSMutableAttributedString
        string = NSMutableAttributedString(string: text ?? "")

        if icon != ""{
            //进行图文混排
            var textAttachment:NSTextAttachment
            textAttachment = NSTextAttachment()
            textAttachment.image = UIImage(named:icon ?? "")
            textAttachment.bounds = CGRect(x: 10, y: 0, width: 11, height: 11)
            var textAttachmentString:NSAttributedString
            textAttachmentString = NSAttributedString(attachment: textAttachment)
            //在城市名称后插入图片
            string.insert(textAttachmentString, at: 0)
        }

        hud.bezelView.color = .black
        hud.contentColor = UIColor.white
        hud.mode = .customView
        hud.detailsLabel.attributedText = string
        hud.showHud(true)
        if let delay = delay {
            hud.hideHud(false, delay)
        }
    }

    ///黑框提示
    class func showRedTipHud(text:String){
        
        if initHUD() { return }
        //纯文本模式
        hud.mode = .text
        var string:NSMutableAttributedString
        string = NSMutableAttributedString(string: " \(text)")
        string.addAttributes(convertToNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font) : UIFont.systemFont(ofSize: 12)]), range: NSRange(location: 0, length: string.length))
        //进行图文混排
        var textAttachment:NSTextAttachment
        textAttachment = NSTextAttachment()
        textAttachment.image = UIImage(named: "tip_red")
        textAttachment.bounds = CGRect(x: 0, y: -3, width: 12, height: 12)
        var textAttachmentString:NSAttributedString
        textAttachmentString = NSAttributedString(attachment: textAttachment)
        string.insert(textAttachmentString, at: 0)
        hud.margin = 10
        hud.bezelView.color = .black
        hud.contentColor = UIColor.white
        hud.detailsLabel.attributedText = string
        hud.showHud(true)
        hud.hideHud(false, 1.5)
    }
    
    /// 显示进度条
    /// - Parameters:
    ///   - needInit: app第一次调用此类不显示转圈，要先初始化下
    ///   - text: <#text description#>
    ///   - progress: <#progress description#>
    class func showProgressView(needInit:Bool = false, text: String, progress: Float) {
        if needInit {
            if initHUD() { return }
        }
        hud.mode = .determinate
        hud.bezelView.color = .white
        hud.contentColor = .black
        hud.bezelView.style = .solidColor
        hud.progress = progress
        hud.label.text = text
        hud.detailsLabel.text = nil
        hud.label.transform = CGAffineTransform(translationX: 0, y: 5)
        hud.showHud(true)
    }
}

extension MBProgressHUD {
    
    func showHud(_ animate: Bool) {
        show(animated: animate)
    }
    
    func hideHud(_ animate: Bool) {
        hide(animated: animate)
    }
    
    func hideHud(_ animate: Bool, _ delay: TimeInterval) {
        hide(animated: animate, afterDelay: delay)
    }
    
    func showHud(_ animate: Bool, _ delay: TimeInterval = 1.5, _ execute: (() -> Void)?) {
        DispatchQueue.main.async { [weak self] () in
            self?.showHud(animate)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
                self?.hideHud(false)
                execute?()
            })
        }
    }

}


// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToNSAttributedStringKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.Key: Any] {
	return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
	return input.rawValue
}
